package com.androidservice.dao;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.androidservice.bean.User;

@Repository
public class UserDao extends AbstractDao<User>{

	public UserDao() {
		super(User.class);
	}
	
	public User findUserByUid(int uid){
		Query query = entityManager.createQuery("select u from User u where u.uid =?1");
		query.setParameter(1, uid);
		
		return (User)query.getSingleResult();
	}


	public boolean findUserByName(String name,String password){
		Query query = entityManager.createQuery("select u from User u where u.name = ?1 and u.password = ?2");
		query.setParameter(1, name);
		query.setParameter(2, password);
		
		if(query.getResultList().size() > 0){
			return true;
		}
		return false;
	}
	
	public User findUserByName(String name){
		Query query = entityManager.createQuery("select u from User u where u.name = ?1");
		query.setParameter(1, name);
		
		if(query.getResultList().size() > 0){
			return (User)query.getSingleResult();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findAllUser(){
		Query query = entityManager.createQuery("select u from User u");
		
		return query.getResultList();
	}
	
	public void saveUser(User user){
		entityManager.merge(user);
	}
	
	public void saveNewUser(User user){
		entityManager.persist(user);
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findUserByRid(int rid){
		Query query = entityManager.createQuery("select u from User u where u.role.rid = ?1");
		query.setParameter(1, rid);
		
		return query.getResultList();
	}
	
	public void deleteUserByUid(int uid){
		Query query = entityManager.createQuery("delete from User u where u.uid = ?1");
		query.setParameter(1, uid);
		
		query.executeUpdate();
	}
	
	public boolean findUserByCheckName(String name){
		Query query = entityManager.createQuery("select u from User u where u.name = ?1");
		query.setParameter(1, name);
		
		if(query.getResultList().size() > 0){
			return false;
		}
		return true;
	}
	
	public boolean findUserByCheckNameAndUid(String name,int uid){
		Query query = entityManager.createQuery("select u from User u where u.name = ?1 and u.uid <> ?2");
		query.setParameter(1, name);
		query.setParameter(2, uid);
		
		if(query.getResultList().size() > 0){
			return false;
		}
		return true;
	}
}
